<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User\User;
use App\Models\Agent\RatioLog;
use App\Models\Agent\TransferLogs;
use App\Models\Agent\ChaoZongdai;
use App\Models\Record\ZongdaiRecord;
use App\Models\Record\Record;
use App\Models\Lottery\Lottery;

class ZongdaiController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $this->validate($request, [
                "begin_time" => "date",
                "end_time"   => "date"
            ]);

            $begin_time = $request->get("begin_time");
            if ($begin_time) {
                $begin_time = date("Y-m-d", strtotime($begin_time));
            }

            $end_time = $request->get("end_time");
            if ($end_time) {
                $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
            }

            $Zongdai = User::whereRaw("id = zongdai");

            $Zongdai= $this->filters($request, $Zongdai);
            $chaoz = null;
            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $Zongdai= $Zongdai->where("users.chao_zongdai", $chaoz->id);
            }
            if ($request->get("chao_zongdai")) {
                $Zongdai= $Zongdai->where("users.chao_zongdai", $request->get("chao_zongdai"));
            }

            $paginator = $Zongdai->orderBy(DB::raw($request->get("sidx")), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $p) {
                $rows[] = $p;
            }

            if ($rows) {
                $ids = [];
                foreach ($rows as $p) {
                    $ids[] = $p->id;
                }

                $chaoZongdais = ChaoZongdai::get();

                $User = User::select(DB::raw("zongdai, COUNT(id) as c"))->whereIn("zongdai", $ids)->whereRaw("users.zongdai <> users.id")->groupBy("zongdai")->get();

                foreach ($rows as $p) {
                    $p->chao_ratio = 0;
                    foreach ($chaoZongdais as $c) {
                        if ($p->chao_zongdai == $c->id) {
                            $p->chao_ratio = $c->ratio - $p->zong_ratio;
                        }
                    }

                    $p->c1 = 0;
                    foreach ($User as $u) {
                        if ($p->id == $u->zongdai) {
                            $p->c1 = $u->c;
                        }
                    }

                    $rs = "";

                    foreach ($chaoZongdais as $user) {
                        if ($user->id == $p->chao_zongdai) {
                            $rs = $user->name;
                        }
                    }
                    $p->rs = $rs;
                    $p->cm = $chaoz ? round($chaoz->money2/100, 2) : 0;
                }

            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            $rs = "";

            $chaoz = null;
            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $rs = "{$chaoz->id}:{$chaoz->name}";
            } else {
                $chaozongdais = ChaoZongdai::get();
                foreach ($chaozongdais as $user) {
                    if ($rs) {
                        $rs .= ";";
                    }
                    $rs .= "{$user->id}:{$user->name}";
                }
            }

            if ($chaoz) {
                $money = round($chaoz->money/100, 2);
            }else{
                $money = 0;
            }

            return view("agent/zongdai/index", [
                "chaoz"   => $chaoz,
                "rs"      => $rs,
                "money"   => $money,
            ]);
        }
    }

    public function detail(Request $request)
    {
        $this->validate($request, [
            "begin_time" => "date",
            "end_time"   => "date",
        ]);

        $begin_time = $request->get("begin_time");
        if ($begin_time) {
            $begin_time = date("Y-m-d", strtotime($begin_time));
        }

        $end_time = $request->get("end_time");
        if ($end_time) {
            $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
        }

        if ($request->ajax()) {

            $record = new Record();

            if ($begin_time) {
                $record = $record->where("create_time", ">=", $begin_time);
            }
            if ($end_time) {
                $record = $record->where("create_time", "<=", $end_time);
            }
            if ($request->get("zongdai")) {
                $record = $record->where("user_id", $request->get("zongdai"));
            }

            $record = $this->filters($request, $record);
            $record= $record->orderBy(DB::raw($request->get("sidx")), $request->get("sord"));

            $paginator = $record->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $p) {
                $rows[] = $p;
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];
            return response()->json($data);

        } else {
            return view("agent/zongdai/detail");
        }
    }

    public function edit(Request $request)
    {
        $oper = $request->get('oper');

        if ($oper == "add") {

            if ($this->isChaoZongdai()) {
                return response()->json(["success" => false , "message" => "操作失败"]);
            }

            $this->validate($request, [
                "id"         => "required|int",
                "zong_ratio" => "int|min:0|max:100"
            ]);

            $ratio = $request->get("zong_ratio");

            $id = $request->get("id");
            $user = User::find($id);
            if (!$user) {
                return response()->json(["success" => false , "message" => "用户不存在"]);
            }

            if ($user->zongdai == $user->id) {
                return response()->json(["success" => false , "message" => "已是总代"]);

            } else {

                DB::beginTransaction();

                $chaoZongdai = ChaoZongdai::find($request->get("chao_zongdai"));

                if ($ratio > $chaoZongdai->ratio) {
                    return response()->json(["success" => false , "message" => "比率不能大于所属的合伙人"]);
                }

                $user->zongdai      = $user->id;
                $user->bindid       = null;
                $user->zong_ratio   = $ratio;
                $user->chao_zongdai = $chaoZongdai->id;
                $user->save();

                $ids = [$user->id];

                while(1) {

                    $affected_rows = User::whereIn("bindid", $ids)->update(["zongdai" => $user->zongdai , "chao_zongdai" => $user->chao_zongdai]);
                    if ($affected_rows) {
                        $list = User::select("id")->whereIn("bindid", $ids)->get();
                        $ids = [];
                        foreach ($list as $val) {
                            $ids[] = $val->id;
                        }
                    } else {
                        break;
                    }
                }
                DB::commit();
            }
        } else if ($oper == "edit") {

            $this->validate($request, [
                "id"           => "required|integer",
                "chao_zongdai" => "integer",
                "zong_ratio"   => "required|int",
            ]);

            $id = $request->get("id");

            $zongdai = User::find($id);

            $chao = ChaoZongdai::find($request->get("chao_zongdai"));

            if (!$chao) {
                return response()->json(["success" => false , "message" => "选择的合伙人不存在"]);
            }
            if (!$zongdai || $zongdai->id != $zongdai->zongdai) {
                return response()->json(["success" => false , "message" => "该伙伴不存在"]);

            } elseif (!$this->isSameChaoZongdai($zongdai->chao_zongdai)) {
                return redirect()->back()->withInput(["操作失败"]);

            }else {

                $ratio = $request->get("zong_ratio");
                $chaoZongdai = ChaoZongdai::find($request->get("chao_zongdai"));
                if ($ratio > $chaoZongdai->ratio) {
                    return response()->json(["success" => false , "message" => "比率不能大于所属的合伙人"]);
                }
                if($zongdai->zong_ratio != $ratio) {
                    if(date('i') > 50) {
                        return response()->json(["success" => false , "message" => "现在不能设置，请稍后重试"]);
                    }
                    RatioLog::where("user_id", $id)->where("cid", $chaoZongdai->id)->where("is_set", 0)->delete();
                    try{
                        $rel = new RatioLog();
                        $rel->user_id = $id;
                        $rel->time    = date('Y-m-d H:i:s');
                        $rel->ratio   = $ratio;
                        $rel->cid     = $chaoZongdai->id;
                        $rel->is_set  = 0;
                        $rel->save();
                    } catch( \Exception $e) {
                        return response()->json(["success" => false , "message" => "数据库异常:" . $e->getMessage()]);
                    }
                    $ratio = $zongdai->zong_ratio;
                }
                $oldZongdai = $zongdai->chao_zongdai;

                $zongdai->chao_zongdai = $request->get("chao_zongdai");
//                $zongdai->bindid       = 0;
                $zongdai->zong_ratio   = $ratio;
//                var_dump($request->get("desc"));exit;
                $zongdai->desc         = $request->get("desc");
                $zongdai->save();

                if ($oldZongdai != $zongdai->chao_zongdai) {
                    User::where("zongdai", $id)->update(["chao_zongdai" => $request->get("chao_zongdai")]);
                }
                if($ratio != $request->get("zong_ratio")) {
                    return response()->json(["success" => true , "message" => "修改数据成功,".(60-date('i'))."分钟后生效"]);
                }
                return response()->json(["success" => true , "message" => "修改数据成功"]);
            }

        } elseif ($oper == "del") {
            $id = $request->get("id");

            $zongdai = User::find($id);
            if ($zongdai) {

                $count = User::where("zongdai", $zongdai->id)->whereRaw("users.zongdai <> users.id")->count();
                if ($count > 0) {
                    return response()->json(["success" => false , "message" => "已有下属伙伴不能删除"]);
                }

                $zongdai->chao_zongdai = null;
                $zongdai->zongdai = null;
                $zongdai->zong_ratio = 0;
                $zongdai->save();
            }
        }
        return response()->json(["success" => true]);

    }

    public function ratio(Request $request)
    {
        $this->validate($request, [
            "id" => "required|integer",
            "ratio" => "required|integer|min:1|max:100"
        ]);

        if ($this->isChaoZongdai()) {
            $admin = Auth::user();

            $ChaoZongdai = ChaoZongdai::where("email", $admin->email)->first();
        }

        $chao_ratio = $ChaoZongdai->ratio;
        if ($request->get("ratio") > $chao_ratio){
            return redirect()->back()->withErrors("伙伴分成比例不能大于总比例");
        }

        $zongdai = User::find($request->get("id"));
        if (!$zongdai || $zongdai->id != $zongdai->zongdai){
            return redirect()->back()->withErrors("参数错误");
        }

        $zongdai->zong_ratio = $request->get("ratio");
        $zongdai->save();

        return redirect()->back()->withInput(["message" => "重置分成比例成功"]);
    }

    public function record(Request $request)
    {
        if ($request->ajax()){

            $record = ZongdaiRecord::select(DB::raw("
                zongdai_records.id AS `id`,
                number,
                user_id,
                nickname,
                kjcode,
                truncate(zongdai_records.money/100,2) as money,
                truncate(zongdai_records.spend/100,2) as spend,
                ratio,
                chao_zongdai,
                truncate(zongdai_records.win/100,2) as win,
                create_time"));
            $record= $this->filters($request, $record);

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $ChaoZongdai= ChaoZongdai::where("email", $admin->email)->first();
                $record = $record->where("chao_zongdai", $ChaoZongdai->id);
            }
            $paginator = $record->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            $numbers = [];
            $chaoZongdais = ChaoZongdai::get();

            foreach ($paginator as $page){

//                 if ($page->kjcode %2 == 0) {
//                     if($page->kjcode >13){
//                         $page->kjcode .= '(大双)';
//                     }else{
//                         $page->kjcode .= '(小双)';
//                     }
//                 } else {
//                     if($page->kjcode >13){
//                         $page->kjcode .= '(大单)';
//                     }else{
//                         $page->kjcode .= '(小单)';
//                     }
//                 }

                $rs = "";
                foreach ($chaoZongdais as $user) {
                    if ($user->id == $page->chao_zongdai) {
                        $rs = $user->name;
                    }
                }
                $page->rs = $rs;

                $rows[] = $page;
                $numbers[] = $page->number;
            }

            $lotterys = Lottery::select(DB::raw("issue, kjcodes"))->whereIn("issue", $numbers)->get();

            if ($rows){
                foreach ($rows as $row){
                    foreach ($lotterys as $lottery){
                        if ($row->number == $lottery->issue){
                            $row->kjcodes = $lottery->kjcodes;
                        }
                    }
                }
            }
            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            $rs = "";

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $rs = "{$chaoz->id}:{$chaoz->name}";
            } else {
                $chaozongdais = ChaoZongdai::get();
                foreach ($chaozongdais as $user) {
                    if ($rs) {
                        $rs .= ";";
                    }
                    $rs .= "{$user->id}:{$user->name}";
                }
            }

            return view('agent/zongdai/record', ["rs" => $rs]);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 合伙人向伙伴转账
     */
    function transfer(Request $request)
    {
        $this->validate($request, [
            "zongdai_id" => "required|integer",
            "trans_money" => "required|integer"
        ]);
        $rel = new TransferLogs();
        if ($this->isChaoZongdai()) {
            $admin = Auth::user();
            $chaoz = ChaoZongdai::where("email", $admin->email)->first();
            $chao_money = $chaoz->money2 - $rel::where('is_set',0)->where('chao_id',$chaoz->id)->sum('trans_money');
            $chao_money = $chao_money/100;
        }else{
            return response()->json(["success" => false, "message" => "非合伙人不能使用"]);
        }

        DB::beginTransaction();

        $zongdai = User::find($request->get("zongdai_id"));
        $zongdai_money = $zongdai->money/100;

        if (!$zongdai || $zongdai->chao_zongdai != $chaoz->id) {
            return response()->json(["success" => false , "message" => "伙伴ID错误"]);
        }

        $trans_money = $request->get("trans_money");

        if ($trans_money> 0 && $trans_money > $chao_money) {
            return response()->json(["success" => false , "message" => "保险箱余额不足"]);

        } elseif ($trans_money < 0 && $trans_money < -$zongdai_money) {
            return response()->json(["success" => false , "message" => "伙伴余额不足"]);

        } elseif ($trans_money == 0) {
            return response()->json(["success" => false , "message" => "参数错误"]);

        } else {

            // if(date('i') > 50) {
            //     return response()->json(["success" => false , "message" => "现在不能设置，请稍后重试"]);
            // }
            try{
                $rel->zongdai_id = $zongdai->id;
                $rel->chao_id = $chaoz->id;
                $rel->trans_money = $trans_money*100;
                $rel->before = $chaoz->money2 - $rel::where('is_set',0)->where('chao_id',$chaoz->id)->sum('trans_money');
                $rel->after = $rel->before - $trans_money*100;
                $rel->create_time = date("Y-m-d H:i:s");
                $rel->desc = '';
                $rel->is_set = 0;
                $rel->save();
            } catch( \Exception $e) {
                return response()->json(["success" => false , "message" => "数据库异常:" . $e->getMessage()]);
            }

            DB::commit();
        }
        return response()->json(["success" => true,"message" => "修改数据成功,2分钟后生效"]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 合伙人向伙伴转账记录
     */
    function translog(Request $request) {
        if ($request->ajax()) {
            $chaoz = null;
            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $translogs = TransferLogs::where('chao_id',$chaoz->id);
                $Record = $this->filters($request,$translogs);
            }else{
                $Record = $this->filters($request, new TransferLogs());
            }

            if($request->get("zongdai_id")) {
                $Record = $Record->where("zongdai_id", $request->get("zongdai_id"));
            }
            if($request->get("chao_id")) {
                $Record = $Record->where("chao_id", $request->get("chao_id"));
            }
            if($request->get("create_time")) {
                $Record = $Record->where("create_time", $request->get("create_time"));
            }

            if($request->get("is_set")) {
                $Record = $Record->where("is_set", $request->get("is_set"));
            }

            $paginator = $Record->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $page) {
                $page->zongdai_name = User::where('id',$page->zongdai_id)->pluck('nickname');
                $page->chaoz_name = ChaoZongdai::where("id", $page->chao_id)->pluck('name');
                $rows[] = $page;
            }


            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            $chaoz = null;
            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
            }

            return view("agent/zongdai/translog", [
                "chaoz"   => $chaoz,
            ]);
        }

    }
}
